package plugin;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import org.json.JSONObject;

public class UPCDBOrgPlugin implements IProductIDPlugin {

	private final String APIKey = "2316e70001a2757dc55dc64ce0465787";
	private final int ONE_SECOND = 1000;
	
	public UPCDBOrgPlugin(){

	}
	
	@Override
	public String identifyProduct(String barcode) throws Exception {
		String URLString = "http://www.upcdatabase.org/api/json/" + APIKey + "/";
		//pad the barcode to 13 digits. upcdatabase.org won't work if it's not padded to 13 digits
		URLString += "0" + barcode;
		URL url = new URL(URLString);
		URLConnection conn = url.openConnection();
		conn.setConnectTimeout(ONE_SECOND);
		conn.setReadTimeout(ONE_SECOND * 5);
		//read from the website
		BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String nextLine;
		String jsonResponse = "";
		//get the entire response
		while((nextLine = in.readLine()) != null){
			jsonResponse += nextLine;
		}
//		System.out.println(jsonResponse);
		//parse the JSON object
		JSONObject jsonObject = new JSONObject(jsonResponse);
		
		//if the product is valid
//		System.out.println(jsonObject.getString("valid"));
		if(jsonObject.getString("valid").equals("true")){
			//return the product description
			return jsonObject.getString("description");
		}
		else{
			throw new Exception();
		}
	}

}
